package service

import (
	"automation/util"
	"fmt"
	"log"

	"github.com/tebeka/selenium"
	"github.com/tebeka/selenium/chrome"
)

var (
	server        *selenium.Service
	ErrorNotFound error = fmt.Errorf("not found")
)

// 初始化驱动
func SetupDriver() selenium.WebDriver {
	seleniumPath := util.Viper.GetString("server.chrome_driver_path")
	systemPort := util.Viper.GetInt("system.port")
	chromeDriverPort := util.Viper.GetInt("server.chrome_driver_port")
	if seleniumPath == "" {
		log.Fatal("请设置server.chrome_driver_path")
	}

	if systemPort == 0 {
		log.Fatal("请设置system.port")
	}

	if chromeDriverPort == 0 {
		log.Fatal("请设置server.chrome_driver_port")
	}

	//地址处理
	seleniumPath = util.ConvertDiskPath(seleniumPath)

	//初始化
	ops := []selenium.ServiceOption{}
	srv, err := selenium.NewChromeDriverService(seleniumPath, systemPort, ops...)
	if err != nil {
		log.Fatal("启动谷歌浏览器驱动失败:", err)
	}
	server = srv

	caps := selenium.Capabilities{
		"browserName": "chrome",
	}

	baseUrl := util.Viper.GetString("system.base_url")
	if baseUrl == "" {
		baseUrl = "127.0.0.1"
	}

	chromeOptions := chrome.Capabilities{
		DebuggerAddr: fmt.Sprintf("%s:%d", baseUrl, chromeDriverPort),
	}

	//无头模式
	mode := util.Viper.GetBool("reliste.use_small_window_mode")
	if mode {
		chromeOptions.Args = append(chromeOptions.Args, "--headless", "--disable-gpu", "--no-sandbox", "--disable-dev-shm-usage")
	}

	caps.AddChrome(chromeOptions)

	urlPrefix := fmt.Sprintf("http://%s:%d/wd/hub", baseUrl, systemPort)
	driver, err := selenium.NewRemote(caps, urlPrefix)

	if err != nil {
		log.Fatal("请确认是否已经打开了谷歌浏览器:", err)
	}

	return driver
}
